package com.whut.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.whut.mapper.*;
import com.whut.model.*;
import com.whut.service.IntelligentMatchingService;
import com.whut.service.NewFuzzyService;
import com.whut.utils.StringOperate;
import com.whut.utils.pointsCalculate;
import com.whut.v_model.Contractspecialistinfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.formula.functions.T;
import org.hibernate.validator.constraints.NotBlank;
import org.omg.CORBA.FloatSeqHelper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.enterprise.inject.New;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @ClassName NewServiceImpl
 * @Auhtor chr
 * @Description 模糊数学模块
 * @Date 2020/9/23 16:48
 **/
@Slf4j
@Service
public class NewFuzzyServiceImpl implements NewFuzzyService {

    @Resource
    private NewspecialistinfoMapper newspecialistinfoMapper;
    @Resource
    private NewjudgeinfoMapper newjudgeinfoMapper;
    @Resource
    private NewPrefixSystemMapper newprefixsystemMapper;
    @Resource
    private ProblemcollectMapper problemcollectMapper;
    @Resource
    private FuzzyindicatorsMapper fuzzyindicatorsMapper;
    @Resource
    private ProblemCollectDetailMapper problemCollectDetailMapper;
    @Resource
    private NewProblemCollectDetailMapper newProblemCollectDetailMapper;
    @Resource
    private NewfuzzyresultMapper newfuzzyresultMapper;
    @Resource
    private CombinedtermsMapper combinedtermsMapper;
    @Resource
    private NewmembershipinfoMapper newmembershipinfoMapper;
    @Resource
    private ContractinfoMapper ContractinfoMapper;
    @Resource
    private ContractspecialistinfoMapper ContractspecialistinfoMapper;
    @Resource
    private ContractspecialistinfoMapper contractspecialistinfoMapper;
    @Resource
    private NoproblemitemMapper noproblemitemMapper;

    @Override
    public Object getAllSpecialist(Integer curPage, Integer pageSize) {
        if(curPage!=null&&pageSize!=null){
            PageHelper.startPage(curPage,pageSize);
            PageInfo<Newspecialistinfo> newspecialistinfoPageInfo = new PageInfo<>(newspecialistinfoMapper.getAllSpecialist());
            return newspecialistinfoPageInfo;
        }
        return null;
    }

    @Override
    public String addSpecialInfo(Newspecialistinfo newspecialistinfo) {
        newspecialistinfoMapper.insertSelective(newspecialistinfo);
        return "success";
    }

    @Override
    public String updateNewSpecialInfo(Newspecialistinfo newspecialistinfo) {
        newspecialistinfoMapper.updateByPrimaryKeySelective(newspecialistinfo);
        return "success";
    }

    @Override
    public Object getAllNewJudgeInfo(int specialistId, int id3, int nodeLevel) {
        List<Object> list = new ArrayList<>();
        Map<String, Object> map = new HashMap<>();
        List<Object> list1 = new ArrayList<>();
        List<Object> list2 = new ArrayList<>();
        List<Integer> allItemsList = newjudgeinfoMapper.getAllId1(specialistId,id3,nodeLevel);
        for (int i = 0; i < allItemsList.size() + 1; i++) {
            Map<String, Object> map1 = new HashMap<>();
            if (i == 0) {
                map1.put("id", "name");
                map1.put("value", "检查项");
            } else {
                map1.put("id", allItemsList.get(i - 1).toString());
                map1.put("value", newprefixsystemMapper.getName4ByName4Id(allItemsList.get(i - 1)));
            }
            if (i < allItemsList.size()) {
                Map<String, Object> map2 = new HashMap<>();
                map2.put("name", newprefixsystemMapper.getName4ByName4Id(allItemsList.get(i)));
                map2.put("id", allItemsList.get(i));
                for (int j = 0; j < allItemsList.size(); j++) {
                    map2.put(allItemsList.get(j).toString(), newjudgeinfoMapper.getPointById1AndId21(specialistId, allItemsList.get(j), allItemsList.get(i),id3,nodeLevel));
                }
                list2.add(map2);
            }
            list1.add(map1);
        }
        map.put("list1", list1);
        map.put("list2", list2);
        list.add(map);
        return list;
    }

    @Override
    public Object getAllContractInfo(int specialistId) {
        System.out.println("前台数据");
       List<Contractspecialistinfo> csi=ContractspecialistinfoMapper.getContractspecialistinfoByspeciallistid(specialistId);
        List<Object> list = new ArrayList<>();
        for(int i=0;i<csi.size();i++){
            Map<String, Object> map1 = new HashMap<>();
            if(csi.get(i).getContractId()!=null){
            Contractinfo ci= ContractinfoMapper.getClientByContractId1(csi.get(i).getContractId());
            map1.put("client",ci.getClient());
            map1.put("mkey1",csi.get(i).getMkey());
            list.add(map1);}
        }
        return list;
    }

    @Override
    public String addNewJudgeInfos(String judgeInfos) {
        JSONArray list1 = JSON.parseArray(judgeInfos);
        System.out.println("前台数据"+judgeInfos);
        List<Newjudgeinfo> list = JSONObject.parseArray(list1.toJSONString(), Newjudgeinfo.class);
        if(list.size()>0){

            for(int i=0;i<list.size();i++){
                Newjudgeinfo newjudgeinfo =list.get(i);
                newjudgeinfoMapper.insertSelective(newjudgeinfo);
            }
        }
        return "success";
    }

    @Override
    public String deleteByNewSpecialId(int specialistId, int id3, int nodeLevel) {
        newjudgeinfoMapper.deleteByNewSpecialId(specialistId,id3,nodeLevel);
        return "success";
    }

    @Override
    public Object getChooseInfoForNewJudege(int preNum, int nodeDepth) {
        List<ParPrefixSystem> childList;
        if(nodeDepth==6){
            //深度为第六级时，实际是查找当前节点的孙子节点
            childList = newprefixsystemMapper.getGrandSonByDepthAndPreNum(preNum,nodeDepth);
        }else {
            childList = newprefixsystemMapper.getItemByDepthAndPreNum(preNum,nodeDepth);
        }
        ArrayList<Object> list = new ArrayList<>();
        int size = childList.size();
            if(size>0){
                for(int i=0;i<size;i++){
                    HashMap<Object, Object> objectObjectHashMap = new HashMap<>();
                    objectObjectHashMap.put("id",childList.get(i).getNumber());
                    objectObjectHashMap.put("name",childList.get(i).getParameterName());
                    list.add(objectObjectHashMap);
                }
            }
            return list;
    }

    @Override
    public String addNewJudgeItems(int number, int specialistId, int id3, int nodeLevel) {
        List<Integer> allItemsList = newjudgeinfoMapper.getAllId1(specialistId,id3,nodeLevel);
        Newjudgeinfo judgeinfo = new Newjudgeinfo();
        judgeinfo.setId1(number);
        judgeinfo.setId2(number);
        judgeinfo.setId3(id3);
        judgeinfo.setSpecialistId(specialistId);
        judgeinfo.setPoint(0.0);
        judgeinfo.setNodeLevel(nodeLevel);
        newjudgeinfoMapper.insertSelective(judgeinfo);
        for (int i = 0; i < allItemsList.size(); i++) {
            Newjudgeinfo judgeinfo1 = new Newjudgeinfo();
            judgeinfo1.setId1(number);
            judgeinfo1.setId2(allItemsList.get(i));
            judgeinfo1.setId3(id3);
            judgeinfo1.setSpecialistId(specialistId);
            judgeinfo1.setPoint(0.0);
            judgeinfo1.setNodeLevel(nodeLevel);
            newjudgeinfoMapper.insertSelective(judgeinfo1);
            Newjudgeinfo judgeinfo2 = new Newjudgeinfo();
            judgeinfo2.setId2(number);
            judgeinfo2.setId3(id3);
            judgeinfo2.setId1(allItemsList.get(i));
            judgeinfo2.setSpecialistId(specialistId);
            judgeinfo2.setPoint(0.0);
            judgeinfo2.setNodeLevel(nodeLevel);
            newjudgeinfoMapper.insertSelective(judgeinfo2);
        }
        return "success";

    }

    @Override
    public String editNewJudgeInfo(Newjudgeinfo newjudgeinfo) {
        newjudgeinfoMapper.editNewJudgeInfo(newjudgeinfo);
        return "success";
    }

    @Override
    public String deleteSelectedItem(int number, int specialistId, int id3, int nodeLevel) {
        newjudgeinfoMapper.deleteSelectedItem(number,specialistId,id3,nodeLevel);
        return null;
    }

    @Override
    public String deleteSpecialById(int mkey) {
        newspecialistinfoMapper.deleteByPrimaryKey(mkey);
        return "success";
    }
    @Override
    public String deleteContractInfoByMkey(int mkey) {
        System.out.println(mkey);
            ContractspecialistinfoMapper.deleteByPrimaryKey(mkey);
        return "success";
    }

    @Override
    public String addNewAllMemberShipInfo(String memberShipInfos) {
        JSONArray list1 = JSON.parseArray(memberShipInfos);
        List<Newmembershipinfo> list = JSONObject.parseArray(list1.toJSONString(), Newmembershipinfo.class);
        if(list.size()>0){
            for(int i=0;i<list.size();i++){
                Newmembershipinfo newmembershipinfo =list.get(i);
                newmembershipinfoMapper.insertSelective(newmembershipinfo);
            }
        }
        return "success";
    }

    @Override
    public Float newConsistCheck(int specialistId, int id3, int nodeLevel) {
        List<Integer> allItemsList = newjudgeinfoMapper.getAllId1(specialistId,id3,nodeLevel);
        int itemsNum = allItemsList.size();
        float ri = 0;
        switch (itemsNum) {
            case 1:
                ri = 0;
                break;
            case 2:
                ri = 0;
                break;
            case 3:
                ri = 0.58f;
                break;
            case 4:
                ri = 0.90f;
                break;
            case 5:
                ri = 1.12f;
                break;
            case 6:
                ri = 1.24f;
                break;
            case 7:
                ri = 1.32f;
                break;
            case 8:
                ri = 1.41f;
                break;
            case 9:
                ri = 1.45f;
                break;
            case 10:
                ri = 1.49f;
                break;
            case 11:
                ri = 1.52f;
                break;
            case 12:
                ri = 1.54f;
                break;
            case 13:
                ri = 1.56f;
                break;
            case 14:
                ri = 1.58f;
                break;
            case 15:
                ri = 1.59f;
                break;
            case 16:
                ri = 1.5943f;
                break;
            case 17:
                ri = 1.6064f;
                break;
            case 18:
                ri = 1.6133f;
                break;
            case 19:
                ri = 1.6207f;
                break;
            case 20:
                ri = 1.6292f;
                break;
            case 21:
                ri = 1.6385f;
                break;
            case 22:
                ri = 1.6403f;
                break;
            case 23:
                ri = 1.6462f;
                break;
            case 24:
                ri = 1.6497f;
                break;
            case 25:
                ri = 1.6556f;
                break;
            case 26:
                ri = 1.6587f;
                break;
            case 27:
                ri = 1.6631f;
                break;
            case 28:
                ri = 1.667f;
                break;
            case 29:
                ri = 1.6693f;
                break;
            case 30:
                ri = 1.6724f;
                break;
            default:
        }
        List<Float> weightList = new ArrayList<>();
        for (int i = 0; i < itemsNum; i++) {
            List<Float> everyLineList = new ArrayList<>();
            for (int j = 0; j < itemsNum; j++) {
                everyLineList.add(newjudgeinfoMapper.getEveryLine(allItemsList.get(j), allItemsList.get(i), specialistId,id3,nodeLevel));
            }
            //每个检查项列对应的几何平均值
            weightList.add(StringOperate.multiply(everyLineList));
        }
        //标准化
        List<Float> wiList = StringOperate.normalization(weightList);
        float allAwi = 0;
        for (int i = 0; i < itemsNum; i++) {
            float innerAllAwi = 0;
            List<Float> everyLineList = new ArrayList<>();
            for (int k = 0; k < itemsNum; k++) {
                everyLineList.add(newjudgeinfoMapper.getEveryLine(allItemsList.get(k), allItemsList.get(i), specialistId,id3,nodeLevel));
            }
            for (int j = 0; j < itemsNum; j++) {
                innerAllAwi += everyLineList.get(j) * wiList.get(j);
            }
            allAwi += innerAllAwi / wiList.get(i);

        }
        float result = (allAwi / itemsNum - itemsNum) / (itemsNum - 1) / ri;
        return result;
    }

    @Override
    public Object getAllNewJudgeResult(int checkId, int operator, int calcDepth, int firstId) {
        DecimalFormat df = new DecimalFormat("0.00");
        DecimalFormat df2 = new DecimalFormat("0.000");
        DecimalFormat df4 = new DecimalFormat("0.0000");
        List<Object> list = new ArrayList<>();
        List<List<Float>> Alllist2 = new ArrayList<>();//保存第二级权重记录
        List<List<Float>> Alllist3 = new ArrayList<>();//保存第三级权重记录
        List<List<Float>> Alllist4 = new ArrayList<>();//保存第三级权重记录
//        List<Object> list4 = new ArrayList<>();//保存第四级权重记录
        Map<String, Object> map = new HashMap<>();
        List<Integer> specialistIds = contractspecialistinfoMapper.getSpecialistByCheckId(checkId);
        //若该项目下无专家则使用默认专家号，specialistId = 1
        if(specialistIds.size()==0){
            specialistIds.add(1);
        }
        //看检查的第二级id是否唯一
        List<Integer> allSecondId = problemcollectMapper.getAllSecondIdByCheck(checkId,firstId);
        if(allSecondId.size()>1){return "error";}
        int id3 = allSecondId.get(0);

        List<Integer> ThirdList1 = newProblemCollectDetailMapper.getAllThirdIdByFirstId(checkId,firstId);
        //无问题项添加，并去重
        List<Integer> noproblemThirdids = noproblemitemMapper.getThirdIdBycheckidAndFirstId(checkId,firstId);
        if(noproblemThirdids.size()!=0) {
            ThirdList1.addAll(noproblemThirdids);
            ThirdList1 = delRepeat(ThirdList1);
        }
        List<Newspecialistinfo> specialistList = newspecialistinfoMapper.getAllSpecialistInfoById3(id3);
        List<Integer> forthList = new ArrayList<>();
        List<Integer> fifthList = new ArrayList<>();
        int spNum = specialistList.size();
        int thirdNum = ThirdList1.size();
        //进行合并，查找合并项
        List<Integer> ThirdList = new ArrayList<>();
        for(int i= 0 ;i<thirdNum;i++){
            Integer target = combinedtermsMapper.getTargetByCombinedTerm(ThirdList1.get(i));
            if(null == target){
                ThirdList.add(ThirdList1.get(i));
            }else{
                int index = ThirdList.indexOf(target);
                if(index==-1){
                    ThirdList.add(target);
                }
            }
        }
        thirdNum = ThirdList.size();
//        log.info("ThirdList:{}",ThirdList);
        List<Integer> countList = new ArrayList<>();
        List<Integer> countList2 = new ArrayList<>();
        for (int i = 0; i < spNum; i++) {
            countList = new ArrayList<>();
            countList2 = new ArrayList<>();
            forthList = new ArrayList<>();
            fifthList = new ArrayList<>();
            List<Float> list2 = new ArrayList<>();//保存第二级权重记录
            List<Float> list3 = new ArrayList<>();//保存第三级权重记录
            List<Float> list4 = new ArrayList<>();//保存第四级权重记录
            //保存模型第二层的权重向量
            List<Float> secondWeightList = new ArrayList<>();
            //保存一条专家一级判断权重记录
            HashMap<Object, Object> map1 = new HashMap<>();
            //专家权重
            Float judgeWeight = (float) pointsCalculate.getPercentInstance(specialistList.get(i).getJudgeWeight());

            map1.put("name",specialistList.get(i).getName());
//            log.info("map_special:{}",map1);
            for (int k = 0; k < thirdNum; k++) {
                List<Float> thirdWeightList = new ArrayList<>();
                List<Float> everyLineList = new ArrayList<>();
                for (int m = 0; m < thirdNum; m++) {
                    Object res = newjudgeinfoMapper.getEveryLine(ThirdList.get(m), ThirdList.get(k), specialistList.get(i).getMkey(),id3,2);
                    everyLineList.add(res==null?(float)0.0:(float)res);
                }
                //取专家判断矩阵每列的几何平均数
                secondWeightList.add(StringOperate.multiply(everyLineList));

                //查找该第三级下的第四级(是否是合并项)
                //查找到合并的子项
                List<Integer> combinedList = combinedtermsMapper.getCombinedTerms(ThirdList.get(k));
//                log.info("combinedList1:{}",combinedList);
                List<Integer> fourthList = new ArrayList<>();
                if(combinedList==null||combinedList.size()==0){
                    //不是合并项,新增无问题项4级id，并去重
                    fourthList = newProblemCollectDetailMapper.getAllFourthIdByCheckIdAndThirdId(checkId,ThirdList.get(k));
                    List<Integer> noproblemFourthids = noproblemitemMapper.getFourthidByCheckIdAndThirdId(checkId,ThirdList.get(k));
                    if(noproblemFourthids.size()!=0){
                        fourthList.addAll(noproblemFourthids);
                        fourthList = delRepeat(fourthList);
                    }
                }else{
                    for(int l=0;l<combinedList.size();l++){
                        if(ThirdList1.indexOf(combinedList.get(l))!=-1){
                            List<Integer> tmpList = newProblemCollectDetailMapper.getAllFourthIdByCheckIdAndThirdId(checkId,combinedList.get(l));
                            fourthList.addAll(tmpList);
                        }
                    }
                }
                forthList.addAll(fourthList);
//                log.info("id:{}---fourth：{}---ThirdList1:{}",ThirdList.get(k),forthList,ThirdList1);
                log.info("第四级id,forthList:{}",forthList);
                //放到对应的第三级的体系名称
                //String thirdName = ThirdList.get(k).toString();
                //查询第四级的权重
                int fourthNum = fourthList.size();
                countList.add(fourthNum);
                for(int j = 0;j<fourthNum;j++){
//                    Map map2 = new HashMap();
//                    map2.put("pre",thirdName);
//                    map2.put("id",newprefixsystemMapper.getName4ByName4Id(fourthList.get(j)));
//                    map2.put("value",fourthList.get(j));

                    List<Float> everyLineList2 = new ArrayList<>();
                    for(int p= 0;p < fourthNum;p++){
                        Object res = newjudgeinfoMapper.getEveryLine(fourthList.get(p),fourthList.get(j),specialistList.get(i).getMkey(),ThirdList.get(k),3);
                        everyLineList2.add(res==null?(float)0.0:(float)res);
                    }
                    //模型第三级判断矩阵的每列
                    thirdWeightList.add(StringOperate.multiply(everyLineList2));
//                    log.info("thirdWeightList/everyLine:{}",thirdWeightList);
                    if(calcDepth==2){
                        HashMap<Object, Object> map4 = new HashMap<>();
                        map4.put("name",specialistList.get(i).getName());
                        //需要计算体系第六级矩阵的权重，根据第四级
                        List<Float> fourthWeightList =  new ArrayList<>();
                        List<Integer> fifthidList = newProblemCollectDetailMapper.getAllFifthIdBycheckIdAndFourthId(checkId,fourthList.get(j));
                        //新增无问题项功能，通过checkId和四级Id,在[dbo].[uncheckedItems]查询六层级id添加fifthidList
                        List<Integer> noproblemfifthids = newprefixsystemMapper.getNoProblemFifthids(checkId,fourthList.get(j));
                        if(noproblemfifthids.size()!=0) {
                            fifthidList.addAll(noproblemfifthids);
                            fifthidList = delRepeat(fifthidList);//去重
                        }
                        log.info("第五级id,fifthidList:{}",fifthidList);
                        int sixNum = fifthidList.size();
                        countList2.add(sixNum);
                        for(int a = 0;a<sixNum;a++){
                            //模型第四级判断矩阵的列
                            List<Float> everyLineList3 = new ArrayList<>();
                            for(int b=0;b<sixNum;b++){
//                                Object res = newjudgeinfoMapper.getEveryLine(fourthList.get(b),fourthList.get(a),specialistList.get(i).getMkey(),fourthList.get(j),6);
                                Object res = newjudgeinfoMapper.getEveryLine(fifthidList.get(b),fifthidList.get(a),specialistList.get(i).getMkey(),fourthList.get(j),4);
                                everyLineList3.add(res==null?(float)0.0:(float)res);
                            }
                            fourthWeightList.add(StringOperate.multiply(everyLineList3));
                        }
                        fifthList.addAll(fifthidList);
                        //TODO:查找该第五级下的第四级(是否是合并项)

                        //对第四级判断权重标准化
                        List<Float> wiList3 = StringOperate.normalization(fourthWeightList);
                        for(int a=0;a<sixNum;a++){
//                            map4.put(sixthList.get(a).toString(),wiList3.get(a));
                            list4.add(wiList3.get(a)*judgeWeight);
                        }
//                        list4.add(map4);
//                        log.info("list4:{}",list4);
                    }

                }
                //将得到第三级的专家几何的平均数向量标准化
                List<Float> wiList2 = StringOperate.normalization(thirdWeightList);
                for(int j=0;j<fourthNum;j++){
//                    HashMap<Object, Object> map2 = new HashMap<>();
//                    //保存加权后的权值
//                    map2.put("pre",thirdName);
//                    map2.put("fouthName",fourthList.get(j).toString());
//                    map2.put("value",wiList2.get(j)*judgeWeight);
                    list3.add(wiList2.get(j)*judgeWeight);
                }
//                log.info("list3:{}",list3);
            }

//            Map<String, Object> map2 = new HashMap<>();
//            map2.put("name", specialistList.get(i).getName());
//            for (int j = 0; j < allItemsList.size(); j++) {
//                map2.put(allItemsList.get(j).toString(), wiList.get(j));
//                Float judgeWeight = (float) pointsCalculate.getPercentInstance(specialistList.get(i).getJudgeWeight());
//                //对权重与专家权重进行加权
//                allWeightList.add(wiList.get(j) * judgeWeight);
//            }
            //所有专家的判断向量结果
//            list2.add(map2);
            //将得到第三级的专家几何的平均数向量标准化
            List<Float> wiList1 = StringOperate.normalization(secondWeightList);
            for(int i1=0;i1<thirdNum;i1++){
//                Map<Object,Object> map2=new HashMap<>();
//                //保存加权后的结果
//                map2.put("value",wiList1.get(i1)*judgeWeight);
//                map2.put("thirdName",ThirdList.get(i1).toString());
                //保存到list2（每个专家的第二级判断权重）
                list2.add(wiList1.get(i1)*judgeWeight);
            }
            Alllist2.add(list2);
            Alllist3.add(list3);
            Alllist4.add(list4);
            //保存第二级的权重

        }
        log.info("Alllist2：{},Alllist3:{},Alllist4:{}",Alllist2,Alllist3,Alllist4);
//        log.info("spNum{}",spNum);
        if(spNum==0){
            return "error";
        }
        float sum=0;
        NumberFormat pf = NumberFormat.getPercentInstance();
        try {
            Number parse = pf.parse(specialistList.get(0).getJudgeWeight());

            sum= Float.parseFloat(parse.toString());
        } catch (ParseException e) {
            e.printStackTrace();
        }
//        log.info("sum_specialistList:{}",sum);

        List<Float> list2 = Alllist2.get(0);
        List<Float> list3 = Alllist3.get(0);
        List<Float> list4 = Alllist4.get(0);
        for(int i=1;i<spNum;i++){
            //总权重
            try {
                Number parse = pf.parse(specialistList.get(i).getJudgeWeight());
                sum+=Float.parseFloat(parse.toString());
            } catch (ParseException e) {
                e.printStackTrace();
            }

            List<Float> list5 = Alllist2.get(i);
            List<Float> list6= Alllist3.get(i);
            List<Float> list7 = Alllist4.get(i);
            for(int j=0;j<thirdNum;j++){
                list2.set(j,list2.get(j)+list5.get(j));
            }
            for (int j=0;j<list3.size();j++){
                list3.set(j,list3.get(j)+list6.get(j));
            }
            for (int j=0;j<list4.size();j++){
                list4.set(j,list4.get(j)+list7.get(j));
            }
        }
        //对权重归一
        for(int j=0;j<thirdNum;j++){
            list2.set(j,list2.get(j)/sum);
        }
        for (int j=0;j<list3.size();j++){
            list3.set(j,list3.get(j)/sum);
        }
        for (int j=0;j<list4.size();j++){
            list4.set(j,list4.get(j)/sum);
        }
        log.info("list2:{},list3:{},list4:{}",list2,list3,list4);

        //假设隶属度计算式已有
        List<Object> result = new ArrayList<>();
        float resultPoint=0;
        int maxIndexTemp = 0;
        //保存安全实体的模糊结果向量
        List<Float> resultList = new ArrayList<>();
        if(calcDepth==1){
//            List<Integer> thirdList = problemCollectDetailMapper.getAllThirdIdByFirstId(checkId,1);
//            List<Integer> forthList = problemCollectDetailMapper.getAllFourthIdByCheckIdAndFirstId(checkId,1);

            //计算第四级
            int countsize = countList.size();
            int start=0,end=0;

            //保存子项第三级的权重
            List<Double> weight3List = new ArrayList<>();
            List<Double> risk03list = new ArrayList<>();
            List<Double> risk13list = new ArrayList<>();
            List<Double> risk23list = new ArrayList<>();
            List<Double> risk33list = new ArrayList<>();
            List<Double> risk43list = new ArrayList<>();
            //保存所有的隶属度
            List<List<Float>> Allbaserisks = new ArrayList<>();
            for(int i=0;i<countsize;i++) {
                start = end;
                end = start+countList.get(i);
                for(int j=start;j<end;j++) {
                    //获取各个风险等级对应的问题数量
//                   int risk0Num =  problemCollectDetailMapper.getRiskPointCount(checkId,forthList.get(j),"提醒");
                    int risk1Num = newProblemCollectDetailMapper.getRiskPointCount(checkId, forthList.get(j), "1");
                    int risk2Num = newProblemCollectDetailMapper.getRiskPointCount(checkId, forthList.get(j), "2");
                    int risk3Num = newProblemCollectDetailMapper.getRiskPointCount(checkId, forthList.get(j), "3");
                    int risk4Num = newProblemCollectDetailMapper.getRiskPointCount(checkId, forthList.get(j), "4");
                    //设置特征值数量list
                    List<Integer> risksNum = new ArrayList<>();
                    risksNum.add(risk1Num);
                    risksNum.add(risk2Num);
                    risksNum.add(risk3Num);
                    risksNum.add(risk4Num);
                    //根据计算式得到各个风险等级隶属度
                    float risk0point;
                    float risk1point;
                    float risk2point;
                    float risk3point;
                    float risk4point;
                    //查找数据
                    List<Float> risksPoint = findMemberShipByRisksNum(risksNum,specialistIds,operator);
                    if (risksPoint == null){//专家矩阵没有录入完全
                        return "error_专家隶属度录入不全";
                    }
                    //测试，给定假数据
                    risk0point = risksPoint.get(0);
                    risk1point = risksPoint.get(1);
                    risk2point = risksPoint.get(2);
                    risk3point = risksPoint.get(3);
                    risk4point = risksPoint.get(4);
                    //保存到数组，用于计算得分
                    List<Float> fourthRiskList = new ArrayList<>();
                    fourthRiskList.add(risk0point);
                    fourthRiskList.add(risk1point);
                    fourthRiskList.add(risk2point);
                    fourthRiskList.add(risk3point);
                    fourthRiskList.add(risk4point);
                    //归一化处理
//                   List<Float> correctFourthRiskList = correctRisk(fourthRiskList,"0.00");
                    Allbaserisks.add(fourthRiskList);//保存所有的基本隶属度
//                    log.info("Allrisks:{}", Allbaserisks);
                }
            }
            //通过隶属度进行权重修正
            log.info("fix_operator:{}|countList:{}",operator,countList);
            log.info("list2:{}-list3:{}",list2,list3);
            log.info("Allrisks:{}", Allbaserisks);
            fixing(operator,list2,list3,countList,Allbaserisks);

            //进行隶属度计算
            start=0;
            end=0;
            for(int i=0;i<countsize;i++){
                weight3List.add(Double.valueOf(String.valueOf(list2.get(i))));
                start = end;
                end = start+countList.get(i);
                //保存子项第四级的权重
                List<Double> weightList = new ArrayList<>();
                List<Double> risk0list = new ArrayList<>();
                List<Double> risk1list = new ArrayList<>();
                List<Double> risk2list = new ArrayList<>();
                List<Double> risk3list = new ArrayList<>();
                List<Double> risk4list = new ArrayList<>();

                for(int j=start;j<end;j++){
                    weightList.add(Double.valueOf(String.valueOf(list3.get(j))));
                    //获取风险等级
                    List<String> allRisk = newProblemCollectDetailMapper.allRiskPointListNotTiXing(checkId,forthList.get(j));
                    if(allRisk.size()==0){
                        //在问题表中查找不到问题的risk数量，因为无问题项不会存在于问题表中，需要对于每一条新增一个risk=0的数据
                        allRisk.add("0");
                    }
                    //获取各个风险等级对应的问题数量
                    //TODO:简化下面代码中的冗余项，如隶属度已存在Allbaserisks列表里
//                    int risk0Num =  problemCollectDetailMapper.getRiskPointCount(checkId,forthList.get(j),"提醒");
                    int risk1Num =  newProblemCollectDetailMapper.getRiskPointCount(checkId,forthList.get(j),"1");
                    int risk2Num =  newProblemCollectDetailMapper.getRiskPointCount(checkId,forthList.get(j),"2");
                    int risk3Num =  newProblemCollectDetailMapper.getRiskPointCount(checkId,forthList.get(j),"3");
                    int risk4Num =  newProblemCollectDetailMapper.getRiskPointCount(checkId,forthList.get(j),"4");
                    //设置特征值数量list
                    List<Integer> risksNum = new ArrayList<>();
                    risksNum.add(risk1Num);
                    risksNum.add(risk2Num);
                    risksNum.add(risk3Num);
                    risksNum.add(risk4Num);

                    //根据计算式得到各个风险等级隶属度
                    float risk0point=0f;
                    float risk1point=0f;
                    float risk2point=0f;
                    float risk3point=0f;
                    float risk4point=0f;
                    //查找数据
                    List<Float> risksPoint = findMemberShipByRisksNum(risksNum,specialistIds,operator);
                    if (risksPoint == null){//专家矩阵没有录入完全
                        return "error_专家隶属度录入不全";
                    }
                    //测试，给定假数据
                    risk0point=risksPoint.get(0);
                    risk1point=risksPoint.get(1);
                    risk2point=risksPoint.get(2);
                    risk3point=risksPoint.get(3);
                    risk4point=risksPoint.get(4);
                    //保存到对应风险等级列
//                    risk0list.add(Double.valueOf(String.valueOf(risk0point)));
//                    risk1list.add(Double.valueOf(String.valueOf(risk1point)));
//                    risk2list.add(Double.valueOf(String.valueOf(risk2point)));
//                    risk3list.add(Double.valueOf(String.valueOf(risk3point)));
//                    risk4list.add(Double.valueOf(String.valueOf(risk4point)));
                    risk0list.add(Double.valueOf(String.valueOf(Allbaserisks.get(j).get(0))));
                    risk1list.add(Double.valueOf(String.valueOf(Allbaserisks.get(j).get(1))));
                    risk2list.add(Double.valueOf(String.valueOf(Allbaserisks.get(j).get(2))));
                    risk3list.add(Double.valueOf(String.valueOf(Allbaserisks.get(j).get(3))));
                    risk4list.add(Double.valueOf(String.valueOf(Allbaserisks.get(j).get(4))));
                    //保存到数组，用于计算得分
                    List<Float> fourthRiskList=new ArrayList<>();
                    fourthRiskList.add(risk0point);
                    fourthRiskList.add(risk1point);
                    fourthRiskList.add(risk2point);
                    fourthRiskList.add(risk3point);
                    fourthRiskList.add(risk4point);
                    //归一化处理
//                    List<Float> correctFourthRiskList = correctRisk(fourthRiskList,"0.00");

                    List<Float> correctFourthRiskList = Allbaserisks.get(j);
//                    List<Float> correctFourthRiskList = fourthRiskList;
                    //最大值下标
                    int maxIndex = getCombinedMaxRiskIndex(Allbaserisks.get(j));
//                    int maxIndex = getCombinedMaxRiskIndex(fourthRiskList);
                    String itemRisk = "";
                    switch (maxIndex) {
                        case 0:
                            itemRisk = "可忽略风险";
                            break;
                        case 1:
                            itemRisk = "可容忍风险";
                            break;
                        case 2:
                            itemRisk = "可接受风险";
                            break;
                        case 3:
                            itemRisk = "不可接受风险";
                            break;
                        case 4:
                            itemRisk = "拒绝接受风险";
                            break;
                        default:
                    }

                    float fourthItemPoint = calcPoint(Allbaserisks.get(j));
//                    float fourthItemPoint = calcPoint(fourthRiskList);
                    for(int k=0;k<allRisk.size();k++){
                        int riskNum = newProblemCollectDetailMapper.getRiskPointCount(checkId,forthList.get(j),allRisk.get(k));
                        HashMap<Object, Object> map1 = new HashMap<>();
                        map1.put("firstLevelIndicators","实体");
                        map1.put("secondIndicator",newprefixsystemMapper.getName4ByName4Id(ThirdList.get(i)));
                        map1.put("secondWeight",df2.format(list2.get(i)));
                        map1.put("thirdLevelIndicator",newprefixsystemMapper.getName4ByName4Id(forthList.get(j)));
                        map1.put("thirdWeight",df2.format(list3.get(j)));
                        map1.put("risks",allRisk.get(k));
                        map1.put("riskNum",riskNum);
                        map1.put("thirdLevelPoint",df.format(fourthItemPoint));
                        map1.put("thirdRiskLevel",itemRisk);
                        map1.put("risk0",df4.format(correctFourthRiskList.get(0)));
                        map1.put("risk1",df4.format(correctFourthRiskList.get(1)));
                        map1.put("risk2",df4.format(correctFourthRiskList.get(2)));
                        map1.put("risk3",df4.format(correctFourthRiskList.get(3)));
                        map1.put("risk4",df4.format(correctFourthRiskList.get(4)));
                        log.info("list1map1:{}",map1);
                        Newfuzzyresult newfuzzyresult = newfuzzyresultMapper.getNewFuzzyResultByCheckIdAndItemId(checkId,forthList.get(j));
                        if (newfuzzyresult==null){
                            Newfuzzyresult newfuzzyresult1 = new Newfuzzyresult();
                            newfuzzyresult1.setCheckId(checkId);
                            newfuzzyresult1.setResultType(firstId);
                            newfuzzyresult1.setFirstId(firstId);
                            newfuzzyresult1.setSecondId(allSecondId.get(0));
                            newfuzzyresult1.setRisk0Point(Double.valueOf(correctFourthRiskList.get(0)));
                            newfuzzyresult1.setRisk1Point(Double.valueOf(correctFourthRiskList.get(1)));
                            newfuzzyresult1.setRisk2Point(Double.valueOf(correctFourthRiskList.get(2)));
                            newfuzzyresult1.setRisk3Point(Double.valueOf(correctFourthRiskList.get(3)));
                            newfuzzyresult1.setRisk4Point(Double.valueOf(correctFourthRiskList.get(4)));
                            newfuzzyresult1.setPoint(Double.valueOf(fourthItemPoint));
                            newfuzzyresult1.setDepth(4);
                            newfuzzyresult1.setItemId(forthList.get(j));
                            newfuzzyresult1.setResult(maxIndex);
                            newfuzzyresult1.setSecondweight(Double.valueOf(map1.get("secondWeight").toString()));
                            newfuzzyresult1.setThirdWeight(Double.valueOf(map1.get("thirdWeight").toString()));
                            newfuzzyresultMapper.insertSelective(newfuzzyresult1);
                        }else{
                            newfuzzyresult.setCheckId(checkId);
                            newfuzzyresult.setResultType(firstId);
                            newfuzzyresult.setFirstId(firstId);
                            newfuzzyresult.setSecondId(allSecondId.get(0));
                            newfuzzyresult.setRisk0Point(Double.valueOf(correctFourthRiskList.get(0)));
                            newfuzzyresult.setRisk1Point(Double.valueOf(correctFourthRiskList.get(1)));
                            newfuzzyresult.setRisk2Point(Double.valueOf(correctFourthRiskList.get(2)));
                            newfuzzyresult.setRisk3Point(Double.valueOf(correctFourthRiskList.get(3)));
                            newfuzzyresult.setRisk4Point(Double.valueOf(correctFourthRiskList.get(4)));
                            newfuzzyresult.setPoint(Double.valueOf(fourthItemPoint));
                            newfuzzyresult.setDepth(4);
                            newfuzzyresult.setItemId(forthList.get(j));
                            newfuzzyresult.setResult(maxIndex);
                            newfuzzyresult.setSecondweight(Double.valueOf(map1.get("secondWeight").toString()));
                            newfuzzyresult.setThirdWeight(Double.valueOf(map1.get("thirdWeight").toString()));
                            newfuzzyresultMapper.updateByPrimaryKeySelective(newfuzzyresult);
                        }
                        result.add(map1);
                    }
                }
                //保存到对应风险等级列
//                log.info("weightList:{},risk0list:{},operator:{}",weightList,risk0list,operator);
                Float risk01 = pointsCalculate.operatorByType(weightList,risk0list,operator).floatValue();
                Float risk11 = pointsCalculate.operatorByType(weightList,risk1list,operator).floatValue();
                Float risk21 = pointsCalculate.operatorByType(weightList,risk2list,operator).floatValue();
                Float risk31 = pointsCalculate.operatorByType(weightList,risk3list,operator).floatValue();
                Float risk41 = pointsCalculate.operatorByType(weightList,risk4list,operator).floatValue();
                //归一化
                List<Float> riskList1 = new ArrayList<>();
                riskList1.add(risk01);
                riskList1.add(risk11);
                riskList1.add(risk21);
                riskList1.add(risk31);
                riskList1.add(risk41);
                List<Float> newRiskList1 = StringOperate.normalization(riskList1);
                risk03list.add(Double.valueOf(String.valueOf(newRiskList1.get(0))));
                risk13list.add(Double.valueOf(String.valueOf(newRiskList1.get(1))));
                risk23list.add(Double.valueOf(String.valueOf(newRiskList1.get(2))));
                risk33list.add(Double.valueOf(String.valueOf(newRiskList1.get(3))));
                risk43list.add(Double.valueOf(String.valueOf(newRiskList1.get(4))));
//                risk13list.add(pointsCalculate.operatorByType(weightList,risk1list,operator));
//                risk23list.add(pointsCalculate.operatorByType(weightList,risk2list,operator));
//                risk33list.add(pointsCalculate.operatorByType(weightList,risk3list,operator));
//                risk43list.add(pointsCalculate.operatorByType(weightList,risk4list,operator));
            }
            //模糊运算
            float risk0 = pointsCalculate.operatorByType(weight3List,risk03list,operator).floatValue();
            float risk1 = pointsCalculate.operatorByType(weight3List,risk13list,operator).floatValue();
            float risk2 = pointsCalculate.operatorByType(weight3List,risk23list,operator).floatValue();
            float risk3 = pointsCalculate.operatorByType(weight3List,risk33list,operator).floatValue();
            float risk4 = pointsCalculate.operatorByType(weight3List,risk43list,operator).floatValue();
            //保存结果
            resultList.add(risk0);
            resultList.add(risk1);
            resultList.add(risk2);
            resultList.add(risk3);
            resultList.add(risk4);
            //先归一
            resultList = StringOperate.normalization(resultList);
            //计算总得分
            resultPoint = calcPoint(resultList);
//            System.out.println("======================resultPoint:"+resultPoint+",==checkId:"+checkId);
            //合并后最大值下标
            int maxIndex = getCombinedMaxRiskIndex(resultList);
            //修正隶属度结果:总得分超出分项得分的区间
            List<Newfuzzyresult> pointres = newfuzzyresultMapper.getPointAndResultBycheck(checkId);
            if (resultPoint < pointres.get(0).getPoint()){
                resultPoint = pointres.get(0).getPoint().floatValue();
                maxIndex = pointres.get(0).getResult();
            }
            if (resultPoint > pointres.get(pointres.size()-1).getPoint()){
                resultPoint = pointres.get(pointres.size()-1).getPoint().floatValue();
                maxIndex = pointres.get(pointres.size()-1).getResult();
            }
            maxIndexTemp = maxIndex;

            //查询是否已经存在记录
            int count = newfuzzyresultMapper.getCountByCheckIdAndType(checkId,firstId,firstId);
            //将结果改为修正后的结果
//            resultList = correctList;
            //结论保留两位小数，不做修正
            for(int i = 0;i<resultList.size();i++){
                resultList.set(i,Float.valueOf(df.format(resultList.get(i))));
            }
            if(count!=0){
                //更新记录
                Newfuzzyresult newfuzzyresult = newfuzzyresultMapper.getNewFuzzyResultByCheckIdAndType(checkId,firstId,firstId);
                newfuzzyresult.setPoint(Double.valueOf(df.format(resultPoint)));
                newfuzzyresult.setRisk0Point(Double.valueOf(resultList.get(0)));
                newfuzzyresult.setRisk1Point(Double.valueOf(resultList.get(1)));
                newfuzzyresult.setRisk2Point(Double.valueOf(resultList.get(2)));
                newfuzzyresult.setRisk3Point(Double.valueOf(resultList.get(3)));
                newfuzzyresult.setRisk4Point(Double.valueOf(resultList.get(4)));
                newfuzzyresult.setResult(maxIndex);
                newfuzzyresult.setItemId(firstId);
                newfuzzyresultMapper.updateByPrimaryKeySelective(newfuzzyresult);
            }else{
                //新建记录
                Newfuzzyresult newfuzzyresult = new Newfuzzyresult();
                newfuzzyresult.setFirstId(firstId);
                newfuzzyresult.setSecondId(id3);
                newfuzzyresult.setResultType(firstId);
                newfuzzyresult.setCheckId(checkId);
                newfuzzyresult.setPoint(Double.valueOf(df.format(resultPoint)));
                newfuzzyresult.setRisk0Point(Double.valueOf(resultList.get(0)));
                newfuzzyresult.setRisk1Point(Double.valueOf(resultList.get(1)));
                newfuzzyresult.setRisk2Point(Double.valueOf(resultList.get(2)));
                newfuzzyresult.setRisk3Point(Double.valueOf(resultList.get(3)));
                newfuzzyresult.setRisk4Point(Double.valueOf(resultList.get(4)));
                newfuzzyresult.setResult(maxIndex);
                newfuzzyresult.setItemId(firstId);
                newfuzzyresult.setDepth(1);
                newfuzzyresultMapper.insertSelective(newfuzzyresult);
            }
        }else if (calcDepth == 2){
            //保存子项第2级的权重
            List<Double> weight2List = new ArrayList<>();
            //计算第六级
            int countsize = countList.size();
            int countsize2 = countList2.size();
            int start=0,end=0,baseindex=0;
            List<Double> risk03list = new ArrayList<>();
            List<Double> risk13list = new ArrayList<>();
            List<Double> risk23list = new ArrayList<>();
            List<Double> risk33list = new ArrayList<>();
            List<Double> risk43list = new ArrayList<>();
            //保存所有最低级的隶属度
            List<List<Float>> Allbaserisks = new ArrayList<>();
            for(int i=0;i<countsize2;i++) {
                start = end;
                end = start+countList2.get(i);
                for(int j=start;j<end;j++) {
                    //获取各个风险等级对应的问题数量
//                   int risk0Num =  problemCollectDetailMapper.getRiskPointCount(checkId,forthList.get(j),"提醒");
                    int risk1Num = newProblemCollectDetailMapper.getRiskPointCountByFifthId(checkId, fifthList.get(j), "1");
                    int risk2Num = newProblemCollectDetailMapper.getRiskPointCountByFifthId(checkId, fifthList.get(j), "2");
                    int risk3Num = newProblemCollectDetailMapper.getRiskPointCountByFifthId(checkId, fifthList.get(j), "3");
                    int risk4Num = newProblemCollectDetailMapper.getRiskPointCountByFifthId(checkId, fifthList.get(j), "4");
                    //设置特征值数量list
                    List<Integer> risksNum = new ArrayList<>();
                    risksNum.add(risk1Num);
                    risksNum.add(risk2Num);
                    risksNum.add(risk3Num);
                    risksNum.add(risk4Num);
                    //根据计算式得到各个风险等级隶属度
                    float risk0point;
                    float risk1point;
                    float risk2point;
                    float risk3point;
                    float risk4point;
                    //查找数据
                    List<Float> risksPoint = findMemberShipByRisksNum(risksNum,specialistIds,operator);
                    if (risksPoint == null){//专家矩阵没有录入完全
                        return "error_专家隶属度录入不全";
                    }
                    //测试，给定假数据
                    risk0point = risksPoint.get(0);
                    risk1point = risksPoint.get(1);
                    risk2point = risksPoint.get(2);
                    risk3point = risksPoint.get(3);
                    risk4point = risksPoint.get(4);
                    //保存到数组，用于计算得分
                    List<Float> fourthRiskList = new ArrayList<>();
                    fourthRiskList.add(risk0point);
                    fourthRiskList.add(risk1point);
                    fourthRiskList.add(risk2point);
                    fourthRiskList.add(risk3point);
                    fourthRiskList.add(risk4point);
                    //归一化处理
//                   List<Float> correctFourthRiskList = correctRisk(fourthRiskList,"0.00");
                    Allbaserisks.add(fourthRiskList);//保存所有的基本隶属度
                }
            }
            //通过隶属度进行权重修正
            log.info("fix_operator:{}|countList:{}|countList2:{}",operator,countList,countList2);
            log.info("list2:{}-list3:{}-list4:{}",list2,list3,list4);
            log.info("Allrisks:{}", Allbaserisks);
            List<List<List<Float>>> resultcallist = fixing(operator,list2,list3,list4,countList,countList2,Allbaserisks);
            //保存经过模糊运算的所有二层级隶属度
            List<List<Float>> Allsecondrisks = resultcallist.get(0);
            //保存经过模糊运算的所有三层级隶属度
            List<List<Float>> Allthirdrisks = resultcallist.get(1);
            //四层数据储存
            start=0;
            end=0;
            for(int i=0;i<countsize;i++){
                start = end;
                end = start+countList.get(i);
                float secondhItemPoint = calcPoint(Allsecondrisks.get(i));
                for(int j=start;j<end;j++){
                    for (int k=baseindex;k<baseindex+countList2.get(j);k++){
                        List<String> allsixRisks = newProblemCollectDetailMapper.allRiskPointListNotTiXingByfifthid(checkId,fifthList.get(k));
                        if(allsixRisks.size()==0){
                            //在问题表中查找不到问题的risk数量，因为无问题项不会存在于问题表中，需要对于每一条新增一个risk=0的数据
                            allsixRisks.add("0");
                        }
                        //取出隶属度
                        List<Float> correntSixthRiskList = Allbaserisks.get(k);
                        //最大值下标
                        int maxIndex = getCombinedMaxRiskIndex(Allbaserisks.get(k));
                        String itemRisk = "";//风险等级字段
                        switch (maxIndex) {
                            case 0:
                                itemRisk = "可忽略风险";
                                break;
                            case 1:
                                itemRisk = "可容忍风险";
                                break;
                            case 2:
                                itemRisk = "可接受风险";
                                break;
                            case 3:
                                itemRisk = "不可接受风险";
                                break;
                            case 4:
                                itemRisk = "拒绝接受风险";
                                break;
                            default:
                        }
                        //第六层级得分
                        float sixthItemPoint = calcPoint(Allbaserisks.get(k));
                        //插入或更新最低一级的隶属度和得分
                        for(int l=0;l<allsixRisks.size();l++){
                            int riskNum = newProblemCollectDetailMapper.getRiskPointCountByFifthId(checkId,fifthList.get(k),allsixRisks.get(l));
                            HashMap<Object, Object> map1 = new HashMap<>();
                            map1.put("firstLevelIndicators","实体");
                            map1.put("secondIndicator",newprefixsystemMapper.getName4ByName4Id(ThirdList.get(i)));
                            map1.put("secondWeight",df2.format(list2.get(i)));
                            map1.put("thirdLevelIndicator",newprefixsystemMapper.getName4ByName4Id(forthList.get(j)));
                            map1.put("thirdWeight",df2.format(list3.get(j)));
                            map1.put("fourthLevelIndicator",newprefixsystemMapper.getName4ByName4Id(fifthList.get(j)));
                            map1.put("fourthWeight",df2.format(list4.get(k)));
                            map1.put("risks",allsixRisks.get(l));
                            map1.put("riskNum",riskNum);
                            map1.put("secondLevelPoint",df.format(secondhItemPoint));
                            map1.put("thirdLevelPoint",df.format(sixthItemPoint));
                            map1.put("thirdRiskLevel",itemRisk);
                            map1.put("risk0",df4.format(correntSixthRiskList.get(0)));
                            map1.put("risk1",df4.format(correntSixthRiskList.get(1)));
                            map1.put("risk2",df4.format(correntSixthRiskList.get(2)));
                            map1.put("risk3",df4.format(correntSixthRiskList.get(3)));
                            map1.put("risk4",df4.format(correntSixthRiskList.get(4)));
                            log.info("list1map1:{}",map1);
                            Newfuzzyresult newfuzzyresult = newfuzzyresultMapper.getNewFuzzyResultByCheckIdAndItemId(checkId,fifthList.get(j));//解锁数据库插入与更新操作
                            if (newfuzzyresult==null){
                                Newfuzzyresult newfuzzyresult1 = new Newfuzzyresult();
                                newfuzzyresult1.setCheckId(checkId);
                                newfuzzyresult1.setResultType(firstId);
                                newfuzzyresult1.setFirstId(firstId);
                                newfuzzyresult1.setSecondId(allSecondId.get(0));
                                newfuzzyresult1.setRisk0Point(Double.valueOf(correntSixthRiskList.get(0)));
                                newfuzzyresult1.setRisk1Point(Double.valueOf(correntSixthRiskList.get(1)));
                                newfuzzyresult1.setRisk2Point(Double.valueOf(correntSixthRiskList.get(2)));
                                newfuzzyresult1.setRisk3Point(Double.valueOf(correntSixthRiskList.get(3)));
                                newfuzzyresult1.setRisk4Point(Double.valueOf(correntSixthRiskList.get(4)));
                                newfuzzyresult1.setPoint((double) sixthItemPoint);
                                newfuzzyresult1.setDepth(6);
                                newfuzzyresult1.setItemId(fifthList.get(j));
                                newfuzzyresult1.setResult(maxIndex);
                                newfuzzyresult1.setSecondweight(Double.valueOf(map1.get("secondWeight").toString()));
                                newfuzzyresult1.setThirdWeight(Double.valueOf(map1.get("thirdWeight").toString()));
                                newfuzzyresult1.setFourthWeight(Double.valueOf(map1.get("fourthWeight").toString()));
                                newfuzzyresultMapper.insertSelective(newfuzzyresult1);
                            }else{
                                newfuzzyresult.setCheckId(checkId);
                                newfuzzyresult.setResultType(firstId);
                                newfuzzyresult.setFirstId(firstId);
                                newfuzzyresult.setSecondId(allSecondId.get(0));
                                newfuzzyresult.setRisk0Point(Double.valueOf(correntSixthRiskList.get(0)));
                                newfuzzyresult.setRisk1Point(Double.valueOf(correntSixthRiskList.get(1)));
                                newfuzzyresult.setRisk2Point(Double.valueOf(correntSixthRiskList.get(2)));
                                newfuzzyresult.setRisk3Point(Double.valueOf(correntSixthRiskList.get(3)));
                                newfuzzyresult.setRisk4Point(Double.valueOf(correntSixthRiskList.get(4)));
                                newfuzzyresult.setPoint((double) sixthItemPoint);
                                newfuzzyresult.setDepth(4);
                                newfuzzyresult.setItemId(fifthList.get(j));
                                newfuzzyresult.setResult(maxIndex);
                                newfuzzyresult.setSecondweight(Double.valueOf(map1.get("secondWeight").toString()));
                                newfuzzyresult.setThirdWeight(Double.valueOf(map1.get("thirdWeight").toString()));
                                newfuzzyresult.setFourthWeight(Double.valueOf(map1.get("fourthWeight").toString()));
                                newfuzzyresultMapper.updateByPrimaryKeySelective(newfuzzyresult);
                            }
                            result.add(map1);
                        }
                    }
                    baseindex += countList2.get(j);
                }
            }

            //模糊运算得出最顶层分数
            for(int i=0;i<countsize;i++){
                weight2List.add(Double.valueOf(String.valueOf(list2.get(i))));
                List<Float> newRiskList1 = StringOperate.normalization(Allsecondrisks.get(i));
                risk03list.add(Double.valueOf(String.valueOf(newRiskList1.get(0))));
                risk13list.add(Double.valueOf(String.valueOf(newRiskList1.get(1))));
                risk23list.add(Double.valueOf(String.valueOf(newRiskList1.get(2))));
                risk33list.add(Double.valueOf(String.valueOf(newRiskList1.get(3))));
                risk43list.add(Double.valueOf(String.valueOf(newRiskList1.get(4))));
            }
            //模糊运算
            float risk0 = pointsCalculate.operatorByType(weight2List,risk03list,operator).floatValue();
            float risk1 = pointsCalculate.operatorByType(weight2List,risk13list,operator).floatValue();
            float risk2 = pointsCalculate.operatorByType(weight2List,risk23list,operator).floatValue();
            float risk3 = pointsCalculate.operatorByType(weight2List,risk33list,operator).floatValue();
            float risk4 = pointsCalculate.operatorByType(weight2List,risk43list,operator).floatValue();
            //保存顶层隶属度结果
            resultList.add(risk0);
            resultList.add(risk1);
            resultList.add(risk2);
            resultList.add(risk3);
            resultList.add(risk4);
            //先归一
            resultList = StringOperate.normalization(resultList);
            //计算总得分
            resultPoint = calcPoint(resultList);
//            System.out.println("======================resultPoint:"+resultPoint+",==checkId:"+checkId);
            //合并后最大值下标
            int maxIndex = getCombinedMaxRiskIndex(resultList);
            //修正隶属度结果:总得分超出分项得分的区间
            List<Newfuzzyresult> pointres = newfuzzyresultMapper.getPointAndResultBycheck(checkId);
            if (resultPoint < pointres.get(0).getPoint()){
                resultPoint = pointres.get(0).getPoint().floatValue();
                maxIndex = pointres.get(0).getResult();
            }
            if (resultPoint > pointres.get(pointres.size()-1).getPoint()){
                resultPoint = pointres.get(pointres.size()-1).getPoint().floatValue();
                maxIndex = pointres.get(pointres.size()-1).getResult();
            }
            maxIndexTemp = maxIndex;

            //查询是否已经存在记录
            int count = newfuzzyresultMapper.getCountByCheckIdAndType(checkId,firstId,firstId);
            //结论保留两位小数，不做修正
            for(int i = 0;i<resultList.size();i++){
                resultList.set(i,Float.valueOf(df.format(resultList.get(i))));
            }
            //解锁数据库插入与更新操作
            if(count!=0){
                //更新记录
                Newfuzzyresult newfuzzyresult = newfuzzyresultMapper.getNewFuzzyResultByCheckIdAndType(checkId,firstId,firstId);
                newfuzzyresult.setPoint(Double.valueOf(df.format(resultPoint)));
                newfuzzyresult.setRisk0Point(Double.valueOf(resultList.get(0)));
                newfuzzyresult.setRisk1Point(Double.valueOf(resultList.get(1)));
                newfuzzyresult.setRisk2Point(Double.valueOf(resultList.get(2)));
                newfuzzyresult.setRisk3Point(Double.valueOf(resultList.get(3)));
                newfuzzyresult.setRisk4Point(Double.valueOf(resultList.get(4)));
//                newfuzzyresult.setPoint(float2double(resultPoint,df));
//                newfuzzyresult.setRisk0Point(float2double(resultList.get(0),df));
//                newfuzzyresult.setRisk1Point(float2double(resultList.get(1),df));
//                newfuzzyresult.setRisk2Point(float2double(resultList.get(2),df));
//                newfuzzyresult.setRisk3Point(float2double(resultList.get(3),df));
//                newfuzzyresult.setRisk4Point(float2double(resultList.get(4),df));
                newfuzzyresult.setResult(maxIndex);
                newfuzzyresult.setItemId(firstId);
                newfuzzyresultMapper.updateByPrimaryKeySelective(newfuzzyresult);
            }else{
                //新建记录
                Newfuzzyresult newfuzzyresult = new Newfuzzyresult();
                newfuzzyresult.setFirstId(firstId);
                newfuzzyresult.setSecondId(id3);
                newfuzzyresult.setResultType(firstId);
                newfuzzyresult.setCheckId(checkId);
                newfuzzyresult.setPoint(Double.valueOf(df.format(resultPoint)));
                newfuzzyresult.setRisk0Point(Double.valueOf(resultList.get(0)));
                newfuzzyresult.setRisk1Point(Double.valueOf(resultList.get(1)));
                newfuzzyresult.setRisk2Point(Double.valueOf(resultList.get(2)));
                newfuzzyresult.setRisk3Point(Double.valueOf(resultList.get(3)));
                newfuzzyresult.setRisk4Point(Double.valueOf(resultList.get(4)));
                newfuzzyresult.setResult(maxIndex);
                newfuzzyresult.setItemId(firstId);
                newfuzzyresult.setDepth(1);
                newfuzzyresultMapper.insertSelective(newfuzzyresult);
            }



        }
        map.put("list1", result);
        map.put("list2", list2);
        map.put("list3", list3);
        map.put("list4", list4);
        map.put("countList", countList);
        map.put("countList2", countList2);
        map.put("resultList",resultList);//最终(顶级)隶属度
        map.put("point",df.format(resultPoint));//最终(顶级)得分
        map.put("maxIndex",maxIndexTemp);
        list.add(map);
        log.info("list_final:{}",list.toString());
        return list;
    }

    @Override
    public float calcPoint(List<Float> fuzzyConclusion) {
        //分数上限
//        float maxList[] = {100,90,80,70,60};
        //分数下限
        float minList[] = {90,80,70,60,50};
        //得分跨度
        float widthList[]={10,10,10,10,10};
        //系数
        float rlist[] = {10,30,50,70,90};
        //计算R
        float rpoint=0;
        for(int i=0;i<5;i++){
            rpoint+=fuzzyConclusion.get(i)*rlist[i];
        }
        //计算S
//        float spoint = 100-rpoint;
//        System.out.println("rpint:{}"+rpoint);

        //最大风险隶属度
        float maxRisk = Collections.max(fuzzyConclusion);
        //实际最大值下标
//        int realIndex = fuzzyConclusion.lastIndexOf(maxRisk);
//        System.out.println("realIndex: "+realIndex);
        // 合并后最大值下标
        int maxIndex = getCombinedMaxRiskIndex(fuzzyConclusion);
        System.out.println("风险隶属度下标为："+maxIndex);
        //选择S'的计算式
        float sBake=0;
//        switch (realIndex){
//            case 0:{
//                    sBake=(spoint*15)/7-(float)650/7;
//                    break;
//                }
//            case  1:{
//                sBake=(spoint*30)/13-(float)1100/13;
//                break;
//            }
//            case 2:{
//                sBake=(spoint*5)/2-(float)75;
//                //log.info("sBake:{}",sBake);
//                break;
//            }
//            case 3:{
//                sBake=(float) (spoint*30)/13-(float)600/13;
//                break;
//            }
//            case 4:{
//                sBake=(float)(spoint*15)/7-(float)150/7;
//                break;
//            }
//            default: {
//                    break;
//                }
//        }
        //暂存五隶属度值
//        float x1 = fuzzyConclusion.get(0);
//        float x2 = fuzzyConclusion.get(1);
//        float x3 = fuzzyConclusion.get(2);
//        float x4 = fuzzyConclusion.get(3);
//        float x5 = fuzzyConclusion.get(4);
//        //最终得分
//        float point = 0;
        switch (maxIndex){
            case 0:{
                sBake=104-(float)2*rpoint/5;
                break;
                }
            case  1:{
                sBake=(float)290/3-(float)1*rpoint/3;
                break;
            }
            case 2:{
                sBake=(float)345/4-(float)1*rpoint/4;
                break;
            }
            case 3:{
                sBake=80.0f-(float)1*rpoint/4;
                break;
            }
            case 4:{
                sBake=(float)145/2-(float)1*rpoint/4;
                break;
            }
            default: {
                    break;
                }
        }

//        float point = minList[maxIndex]+(widthList[maxIndex]*sBake)/100;
        float point = (float)(Math.round(sBake*100))/100;
        return point;
    }

    @Override
    public List<Object> getUsedItemByDepth(int nodeDepth, int preNum) {
        return newprefixsystemMapper.getUsedItemByDepth(nodeDepth,preNum);
    }

    @Override
    public List<Integer> getAllCombinedTerms(Integer[] targets) {
        List<Integer> list  = Arrays.asList(targets);
        List<Integer> result = combinedtermsMapper.getAllCombinedTerms(list);
        return result;
    }

    @Override
    public List<ParPrefixSystem> getCombinedTermsByTarget(Integer target) {
        List<Integer> combinedList = combinedtermsMapper.getCombinedTerms(target);
        List<ParPrefixSystem> list = new ArrayList<>();
        if(combinedList.size()>0){
            for(int i=0;i<combinedList.size();i++){
                List<ParPrefixSystem> prefixsystemList = newprefixsystemMapper.selectItemByPreNum(combinedList.get(i));
                list.addAll(prefixsystemList);
            }
        }
        return list;
    }
    /**
     * @Author chenhuanru
     * @Description //根据检查项的各个特征值对应的问题数量，获取隶属度
     *                规则：根据最大特征值及次大特征值数量查找，特征值4问题数量最大为7，其他特征值等级问题最大数量为5
     * @Date 13:55 2020-12-05 13:55:17
     * @Param [risksNum]
     * @return java.util.List<java.lang.Float>
     **/
    @Override
    public List<Float> findMemberShipByRisksNum(List<Integer> risksNum) {
        //没有传递list或者list的长度不是4
        if(risksNum==null||risksNum.size()!=4){
            return null;
        }
        List<Float> risksPoint = new ArrayList<>();
        List<String> risksName = Arrays.asList("risk1Num","risk2Num","risk3Num","risk4Num");
        //查找最大特征值
        int index=1;//下标
         for(int i=3;i>0;i--){
            if(risksNum.get(i)!=0){
                index = i;
                break;
            }
         }
         Newmembershipinfo newmembershipinfo;
        if (risksNum.get(0)==0&&risksNum.get(1)==0&&risksNum.get(2)==0&&risksNum.get(3)==0){
            //默认使用专家1,四个特征值为零时
            List<Integer> specialistId = Arrays.asList(1);
            newmembershipinfo = newmembershipinfoMapper.simplefindMemberShipByRisksNum(risksNum.get(0)>5?5:risksNum.get(0),risksNum.get(1)>5?5:risksNum.get(1),risksNum.get(2)>5?5:risksNum.get(2),risksNum.get(3)>7?7:risksNum.get(3),specialistId).get(0);
        }else {
            switch (index){
                case 3:{
                    newmembershipinfo = newmembershipinfoMapper.findMemberShipByRisksNum(risksName.get(index),risksName.get(index-1),risksNum.get(index)>7?7:risksNum.get(index),risksNum.get(index-1)>5?5:risksNum.get(index-1));
                    break;
                }
                default:{
                    newmembershipinfo = newmembershipinfoMapper.findMemberShipByRisksNumAndLastRiskName(risksName.get(index),risksName.get(index-1),risksName.get(index+1),risksNum.get(index)>5?5:risksNum.get(index),risksNum.get(index-1)>5?5:risksNum.get(index-1));
                    break;
                }
            }
        }

         risksPoint.add(Float.valueOf(newmembershipinfo.getRisk0Point().toString()));
         risksPoint.add(Float.valueOf(newmembershipinfo.getRisk1Point().toString()));
         risksPoint.add(Float.valueOf(newmembershipinfo.getRisk2Point().toString()));
         risksPoint.add(Float.valueOf(newmembershipinfo.getRisk3Point().toString()));
         risksPoint.add(Float.valueOf(newmembershipinfo.getRisk4Point().toString()));
        return risksPoint;
    }
    /**
        *Author:YJH
        *Detail:重写查询隶属度方法，根据专家进行融合（2个或以上）
        *Date:2021/8/11-17:11
        *Param:返回五个融合后的隶属度
    */
    public List<Float> findMemberShipByRisksNum(List<Integer> risksNum,List<Integer> specialistId,int operator) {
        //没有传递list或者list的长度不是4
        if(risksNum==null||risksNum.size()!=4){
            return null;
        }
        List<Float> risksPoint = new ArrayList<>();
        List<Newmembershipinfo> newmembershipinfo;
        List<String> risksName = Arrays.asList("risk1Num","risk2Num","risk3Num","risk4Num");
        //查找最大特征值
        int index=1;//下标
        for(int i=3;i>0;i--){
            if(risksNum.get(i)!=0){
                index = i;
                break;
            }
        }
        if (risksNum.get(0)==0&&risksNum.get(1)==0&&risksNum.get(2)==0&&risksNum.get(3)==0){
            newmembershipinfo = newmembershipinfoMapper.simplefindMemberShipByRisksNum(risksNum.get(0)>5?5:risksNum.get(0),risksNum.get(1)>5?5:risksNum.get(1),risksNum.get(2)>5?5:risksNum.get(2),risksNum.get(3)>7?7:risksNum.get(3),specialistId);
        }else {
            switch (index){
                case 3:{
                    newmembershipinfo = newmembershipinfoMapper.findMemberShipByRisksNum1(risksName.get(index),risksName.get(index-1),risksNum.get(index)>7?7:risksNum.get(index),risksNum.get(index-1)>5?5:risksNum.get(index-1),specialistId);
                    break;
                }
                default:{
                    newmembershipinfo = newmembershipinfoMapper.findMemberShipByRisksNumAndLastRiskName1(risksName.get(index),risksName.get(index-1),risksName.get(index+1),risksNum.get(index)>5?5:risksNum.get(index),risksNum.get(index-1)>5?5:risksNum.get(index-1),specialistId);
                    break;
                }
            }
        }
        Newmembershipinfo resultmembership = mergingMembershipinfo(newmembershipinfo,specialistId,operator);
        if (resultmembership==null){
            return null;
        }
        risksPoint.add(Float.valueOf(resultmembership.getRisk0Point().toString()));
        risksPoint.add(Float.valueOf(resultmembership.getRisk1Point().toString()));
        risksPoint.add(Float.valueOf(resultmembership.getRisk2Point().toString()));
        risksPoint.add(Float.valueOf(resultmembership.getRisk3Point().toString()));
        risksPoint.add(Float.valueOf(resultmembership.getRisk4Point().toString()));
        return risksPoint;
    }

    /**
        *Author:YJH
        *Detail:融合多条隶属度为一
        *Date:2021/8/11-17:48
        *Param:<operator>模糊操作数，废弃；待用；
    */
    private Newmembershipinfo mergingMembershipinfo(List<Newmembershipinfo> listmembership, List<Integer> specialistId,int operator){
        //如果隶属度条数不等于专家数，返回空
        if (listmembership.size()!=specialistId.size()){
            return null;
        }
        //如果查询结果只有一条就直接返回
        if (listmembership.size()==1){
            return listmembership.get(0);
        }
        //保存专家权重
        List<Double> specialWeights = new ArrayList<>();
        Double sum = 0d;
        for (Integer i:specialistId){
            String spweight = newspecialistinfoMapper.getSpecialistJudgeWeightById(i);
            double tpweight = pointsCalculate.getPercentInstance(spweight);
            specialWeights.add(tpweight);
            sum += tpweight;
        }
        //归一化
        for (int i=0;i<specialWeights.size();i++){
            specialWeights.set(i,specialWeights.get(i)/sum);
        }
        //定义隶属度列暂存
        List<Double> risk0list = new ArrayList<>();
        List<Double> risk1list = new ArrayList<>();
        List<Double> risk2list = new ArrayList<>();
        List<Double> risk3list = new ArrayList<>();
        List<Double> risk4list = new ArrayList<>();
        for (int i=0;i<specialistId.size();i++){
            risk0list.add(listmembership.get(i).getRisk0Point());
            risk1list.add(listmembership.get(i).getRisk1Point());
            risk2list.add(listmembership.get(i).getRisk2Point());
            risk3list.add(listmembership.get(i).getRisk3Point());
            risk4list.add(listmembership.get(i).getRisk4Point());
        }
        //模糊融合运算
        double risk0 = pointsCalculate.operatorWeightedAverage(specialWeights,risk0list);
        double risk1 = pointsCalculate.operatorWeightedAverage(specialWeights,risk1list);
        double risk2 = pointsCalculate.operatorWeightedAverage(specialWeights,risk2list);
        double risk3 = pointsCalculate.operatorWeightedAverage(specialWeights,risk3list);
        double risk4 = pointsCalculate.operatorWeightedAverage(specialWeights,risk4list);
        log.info("specialWeights:{}",specialWeights);
        log.info("risks:{},{},{},{},{}",risk0,risk1,risk2,risk3,risk4);
        //返回值,直接初始化为需要融合的两个隶属度，问题数量等相同，隶属度不同；更新隶属度即可
        Newmembershipinfo resultmembership = listmembership.get(0);
        resultmembership.setRisk0Point(risk0);
        resultmembership.setRisk1Point(risk1);
        resultmembership.setRisk2Point(risk2);
        resultmembership.setRisk3Point(risk3);
        resultmembership.setRisk4Point(risk4);
        return resultmembership;
    }



    /**
     * @Author chenhuanru
     * @Description //封装一个求解合并后，最大风险值下标的方法
     * @Date 10:56 2020-12-01 10:56:01
     * @Param [fuzzyConclusion]
     * @return java.lang.Integer
     **/
    @Override
    public Integer getCombinedMaxRiskIndex(List<Float> fuzzyConclusion) {
        //最大风险隶属度
        float maxRisk = Collections.max(fuzzyConclusion);
        //最大值下标
        int maxIndex = fuzzyConclusion.lastIndexOf(maxRisk);//(0,1,2,3,4)
        //之前的逻辑
//        if(maxIndex<3){
//            float sumtemp1 = fuzzyConclusion.get(3)+fuzzyConclusion.get(4);//(x4+x5)
//            if (sumtemp1>=fuzzyConclusion.get(0)&&sumtemp1>=fuzzyConclusion.get(1)&&sumtemp1>=fuzzyConclusion.get(2)){
//                return 3;
//            }
//            float sum = fuzzyConclusion.get(0)+fuzzyConclusion.get(1)+fuzzyConclusion.get(2)+fuzzyConclusion.get(3)+fuzzyConclusion.get(4);
//            if (sumtemp1>=sum/2){//(x4+x5)>=(x1+x2+x3+x4+x5)/2?
//                return 3;
//            }else {
//                float sumtemp2 = fuzzyConclusion.get(2)+sumtemp1;//(x3+x4+x5)
//                if (sumtemp2>=sum/2){//(x3+x4+x5)>=(x1+x2+x3+x4+x5)/2?
//                    if (fuzzyConclusion.get(2)>=sumtemp2/2){//x3>=(x3+x4+x5)/2?
//                        return 2;
//                        }
//                    if (fuzzyConclusion.get(2)+fuzzyConclusion.get(3)>=sumtemp2/2){//(x3+x4)>=(x3+x4+x5)/2
//                            float max34 = fuzzyConclusion.get(2);//返回x3,x4中最大下标
//                            if (max34<=fuzzyConclusion.get(3)){
//                                return 3;
//                            }
//                            return 2;
//                    }
//                }else {
//                    float sumtemp3 = fuzzyConclusion.get(1)+sumtemp2;//(x2+x3+x4+x5)
//                    if (sumtemp3>=sum/2){//(x2+x3+x4+x5)>=(x1+x2+x3+x4+x5)/2?
//                        if (fuzzyConclusion.get(1)>=sumtemp3/2){
//                            return 1;
//                        }else if (fuzzyConclusion.get(1)+fuzzyConclusion.get(2)>=sumtemp3/2){//(x2+x3)>=(x2+x3+x4+x5)/2?
//                            float max23 = fuzzyConclusion.get(1);//返回x2,x3中最大下标
//                            if (max23<=fuzzyConclusion.get(2)){
//                                return 2;
//                            }
//                            return 1;
//                        }else if (fuzzyConclusion.get(1)+fuzzyConclusion.get(2)+fuzzyConclusion.get(3)>=sumtemp3/2){//(x2+x3+x4)>=(x2+x3+x4+x5)/2?
//                            float max234 = fuzzyConclusion.get(3);//返回x2,x3,x4最大值下标
//                            for (int i=2;i<=3;i++){
//                                if (fuzzyConclusion.get(i)>max234){
//                                    max234 = fuzzyConclusion.get(i);
//                                }
//                            }
//                            return fuzzyConclusion.indexOf(max234);
//                        }
//                    }else {
//                        return 0;
//                    }
//                }
//            }
//        }
        //--start--yjh:2021-4-27修改
        if (maxIndex<3){
            float sum45 = fuzzyConclusion.get(3)+fuzzyConclusion.get(4);//(x4+x5)
            float sumAll = 0;
            int upper = 0;
            int lower = 0;
            //x1+...+x5的和
            for(int i=0;i<5;i++){
                sumAll+=fuzzyConclusion.get(i);
            }
            //如果X4+X5大于等于X1、且大于等于X2、且大于等于X3，风险区间为4
            if (sum45>=fuzzyConclusion.get(0)&&sum45>=fuzzyConclusion.get(1)&&sum45>=fuzzyConclusion.get(2)){
                return 3;
            }else {
                //确定上界
                if (fuzzyConclusion.get(2)+sum45 >= sumAll/2){
                    //上确界为3
                    upper = 2;
                }else if (fuzzyConclusion.get(1)+fuzzyConclusion.get(2)+sum45 >= sumAll/2){
                    //上确界为2
                    upper = 1;
                } //else upper = 0 (upper初始化为0，则减少一个判断)上确界为1

            }
            //确定下界
            for(int i = upper;i<5;i++){
                if (calculateListfromStartToEnd(fuzzyConclusion,upper,i) >= calculateListfromStartToEnd(fuzzyConclusion,upper,4)/2){
                    lower = i;
                    break;
                }
            }
            //根据上、下确界锁定一个取值区间，取该区间内最大隶属度对应的风险区间
            if (upper == lower){
                //如果上确界=下确界，直接确定风险区间
                return upper;
            }else {
                float temp1 = getMaxInListFromStartToEnd(fuzzyConclusion,upper,lower);
                for (int j = upper;j<=lower;j++){
                    if (fuzzyConclusion.get(j) == temp1){
                        return j;
                    }
                }
            }
        }
        //--end--
        return maxIndex;
    }
    /**
     * Author:yjh
     * Description:<工具方法>计算数组中从位置start到位置end的和</工具方法>
     * Create date:2021/4/27 22:32
     * Param:[List<Float> calist,start,end]
     * Return:Float
     * Modify[]:,,
     */
    private Float calculateListfromStartToEnd(List<Float> calist, int start, int end){
        float result = 0;
        for (int i = start;i<=end;i++){
            result += calist.get(i);
        }
        return result;
    }
    /**
     * Author:yjh
     * Description:<工具方法>计算数组中从位置start到位置end中的最大值</工具方法>
     * Create date:2021/4/27 22:45
     * Param:[List<Float> calist, int start, int end]
     * Return:
     * Modify[]:,,
     */
    private Float getMaxInListFromStartToEnd(List<Float> calist, int start, int end){
        float max = 0;
        for (int i=start;i<=end;i++){
            if (calist.get(i)>max){
                max = calist.get(i);
            }
        }
        return max;
    }

    /**
     * Author:yjh
     * Description:<工具方法>去除list中的重复值</工具方法>
     * Create date:2021/9/15 10:59
     * Param:[]
     * Return:
     * Modify[]:,,
     */
    public static List<Integer> delRepeat(List<Integer> list) {
        return list.stream().distinct().collect(Collectors.toList());
    }

    /**
     * Author:yjh
     * Description:第四层动态权重修正
     * Create date:2021/7/29 11:36
     * Param:[]
     * Return:返回两层计算后的隶属度
     * Modify[]:,,
     */
    public List<List<List<Float>>> fixing(int operator,List<Float> list1,List<Float> list2,List<Float> list3,List<Integer> countList1,List<Integer> countList2,List<List<Float>> allbaserisks){

        int start1=0,start2=0;
        List<List<List<Float>>> resultLists = new ArrayList<>();
        List<List<Float>> temp_all_3 = new ArrayList<>();
        List<List<Float>> temp_all_2 = new ArrayList<>();
        for (int i=0;i<list1.size();i++){
//            log.info("i:{}",i);
            List<Float> temp_list2 = new ArrayList<>();
            List<List<Float>> temp_allsecondrisks = new ArrayList<>();
            List<Double> risk0list3 = new ArrayList<>();//暂存5列特征值
            List<Double> risk1list3 = new ArrayList<>();
            List<Double> risk2list3 = new ArrayList<>();
            List<Double> risk3list3 = new ArrayList<>();
            List<Double> risk4list3 = new ArrayList<>();
            List<Double> temp_double_list2 = new ArrayList<>();//将List<Float>转换为List<Double>进行运算
//            if (countList1.get(i)>1){//若层级内隶属度大于一则进入循环
            for (int j=start1;j<start1+countList1.get(i);j++){
//                log.info(" j:{}",j);
                if (countList2.get(j)>1){//若层级内隶属度大于一则进入循环
                    List<Float> temp_list3 = new ArrayList<>();
                    List<List<Float>> temp_allbaserisks = new ArrayList<>();
                    List<Double> risk0list4 = new ArrayList<>();//暂存5列特征值
                    List<Double> risk1list4 = new ArrayList<>();
                    List<Double> risk2list4 = new ArrayList<>();
                    List<Double> risk3list4 = new ArrayList<>();
                    List<Double> risk4list4 = new ArrayList<>();
                    List<Double> temp_double_list3 = new ArrayList<>();//将List<Float>转换为List<Double>进行运算
                    for (int k=start2;k<start2+countList2.get(j);k++){
//                        log.info("  k:{}",k);
                        //将对应两个4级权重和隶属度加入至列表
                        temp_list3.add(list3.get(k));
//                        temp_double_list3.add(list3.get(k).doubleValue());
                        temp_allbaserisks.add(allbaserisks.get(k));
                        //将每列隶属度存入
                        risk0list4.add(allbaserisks.get(k).get(0).doubleValue());
                        risk1list4.add(allbaserisks.get(k).get(1).doubleValue());
                        risk2list4.add(allbaserisks.get(k).get(2).doubleValue());
                        risk3list4.add(allbaserisks.get(k).get(3).doubleValue());
                        risk4list4.add(allbaserisks.get(k).get(4).doubleValue());
                    }
                    //动态权重修正计算
                    pseudoCodeFixing(temp_list3,temp_allbaserisks);
                    for (int k=start2,l=0;k<start2+countList2.get(j);k++,l++){
                        //更新第三级权重表
                        list3.set(k,temp_list3.get(l));
                        temp_double_list3.add(temp_list3.get(l).doubleValue());
                    }
                    List<Float> resultList = new ArrayList<>();//保存运算结果
                    //模糊运算
                    //log.info("temp_list3:{}|risk0list:{}",temp_double_list3,risk0list);
                    float risk0 = pointsCalculate.operatorByType(temp_double_list3,risk0list4,operator).floatValue();
                    float risk1 = pointsCalculate.operatorByType(temp_double_list3,risk1list4,operator).floatValue();
                    float risk2 = pointsCalculate.operatorByType(temp_double_list3,risk2list4,operator).floatValue();
                    float risk3 = pointsCalculate.operatorByType(temp_double_list3,risk3list4,operator).floatValue();
                    float risk4 = pointsCalculate.operatorByType(temp_double_list3,risk4list4,operator).floatValue();
                    //保存结果
                    resultList.add(risk0);
                    resultList.add(risk1);
                    resultList.add(risk2);
                    resultList.add(risk3);
                    resultList.add(risk4);
                    //相加修正后的权重若和不为1,则归一化
                    Float sum =0f;
                    for (Float item:resultList){
                        sum += item;
                    }
                    if (sum != 1){//归一化
                        for(int l =0;l<resultList.size();l++){
                            Float temp = resultList.get(l)/sum;
                            resultList.set(l,temp);
                        }
                    }
                    temp_all_3.add(resultList);
                }else {//若层级内隶属度==1则直接传递上层该隶属度
//                    log.info("  直接传递4层隶属度");
                    temp_all_3.add(allbaserisks.get(j));
                }
                start2 += countList2.get(j);
            }
            for (int j=start1;j<start1+countList1.get(i);j++){
                temp_list2.add(list2.get(j));
                temp_allsecondrisks.add(temp_all_3.get(j));
//                temp_double_list2.add(list2.get(j).doubleValue());
                risk0list3.add(temp_all_3.get(j).get(0).doubleValue());
                risk1list3.add(temp_all_3.get(j).get(1).doubleValue());
                risk2list3.add(temp_all_3.get(j).get(2).doubleValue());
                risk3list3.add(temp_all_3.get(j).get(3).doubleValue());
                risk4list3.add(temp_all_3.get(j).get(4).doubleValue());
            }
            pseudoCodeFixing(temp_list2,temp_allsecondrisks);
            for (int j=start1,l=0;j<start1+countList1.get(i);j++,l++){
                //更新第二级权重表
                list2.set(j,temp_list2.get(l));
                temp_double_list2.add(temp_list2.get(l).doubleValue());
            }
            List<Float> resultList = new ArrayList<>();//保存运算结果
            //模糊运算
            //log.info("temp_list3:{}|risk0list:{}",temp_double_list3,risk0list);
            float risk0 = pointsCalculate.operatorByType(temp_double_list2,risk0list3,operator).floatValue();
            float risk1 = pointsCalculate.operatorByType(temp_double_list2,risk1list3,operator).floatValue();
            float risk2 = pointsCalculate.operatorByType(temp_double_list2,risk2list3,operator).floatValue();
            float risk3 = pointsCalculate.operatorByType(temp_double_list2,risk3list3,operator).floatValue();
            float risk4 = pointsCalculate.operatorByType(temp_double_list2,risk4list3,operator).floatValue();
            //保存结果
            resultList.add(risk0);
            resultList.add(risk1);
            resultList.add(risk2);
            resultList.add(risk3);
            resultList.add(risk4);
            //相加修正后的权重若和不为1,则归一化
            Float sum =0f;
            for (Float item:resultList){
                sum += item;
            }
            if (sum != 1){//归一化
                for(int l =0;l<resultList.size();l++){
                    Float temp = resultList.get(l)/sum;
                    resultList.set(l,temp);
                }
            }
            temp_all_2.add(resultList);//保存所有隶属度结果
            start1 += countList1.get(i);//下次循环标记更新
        }
        pseudoCodeFixing(list1,temp_all_2);//计算并修改二级权重
        resultLists.add(temp_all_2);
        resultLists.add(temp_all_3);
        log.info("第二层隶属度:{}",temp_all_2);
        log.info("第三层隶属度:{}",temp_all_3);
        log.info("第四层隶属度:{}",allbaserisks);
        return resultLists;
    }

    /**
     * Author:yjh
     * Description:第三层动态权重修正
     * Create date:2021/7/10 23:39
     * Param:[]
     * Return:
     * Modify[0]:yjh,算法更新,隶属度取值不正确
     */
    public List<List<Float>> fixing(int operator,List<Float> list2,List<Float> list3,List<Integer> countList,List<List<Float>> allbaserisks){

        int start=0,end=0;
        List<List<Float>> temp_all = new ArrayList<>();
        //删选出三级隶属度及需要修改的权重，并修改
        for (int i=0;i<countList.size();i++){
            start = end;
            end = start+countList.get(i);
            if (countList.get(i)>1){
                List<Float> temp_list3 = new ArrayList<>();
                List<List<Float>> temp_allbaserisks = new ArrayList<>();
                //暂存5列特征值
                List<Double> risk0list = new ArrayList<>();
                List<Double> risk1list = new ArrayList<>();
                List<Double> risk2list = new ArrayList<>();
                List<Double> risk3list = new ArrayList<>();
                List<Double> risk4list = new ArrayList<>();
                List<Double> temp_double_list3 = new ArrayList<>();//将List<Float>转换为List<Double>进行运算
                for(int j=start;j<end;j++){
                    //将对应两个三级权重和隶属度加入至列表
                    temp_list3.add(list3.get(j));
//                    temp_double_list3.add(list3.get(j).doubleValue());
                    temp_allbaserisks.add(allbaserisks.get(j));
                    //将每列隶属度存入
                    risk0list.add(allbaserisks.get(j).get(0).doubleValue());
                    risk1list.add(allbaserisks.get(j).get(1).doubleValue());
                    risk2list.add(allbaserisks.get(j).get(2).doubleValue());
                    risk3list.add(allbaserisks.get(j).get(3).doubleValue());
                    risk4list.add(allbaserisks.get(j).get(4).doubleValue());
                }
                //动态权重修正计算
                pseudoCodeFixing(temp_list3,temp_allbaserisks);
                for (int j=start,k=0;j<end;j++,k++){
                    //更新第三级权重表
                    list3.set(j,temp_list3.get(k));
                    temp_double_list3.add(temp_list3.get(k).doubleValue());
                }
                List<Float> resultList = new ArrayList<>();//保存运算结果
                //模糊运算
                log.info("temp_list3:{}--list3:{}",temp_double_list3,list3);
                float risk0 = pointsCalculate.operatorByType(temp_double_list3,risk0list,operator).floatValue();
                float risk1 = pointsCalculate.operatorByType(temp_double_list3,risk1list,operator).floatValue();
                float risk2 = pointsCalculate.operatorByType(temp_double_list3,risk2list,operator).floatValue();
                float risk3 = pointsCalculate.operatorByType(temp_double_list3,risk3list,operator).floatValue();
                float risk4 = pointsCalculate.operatorByType(temp_double_list3,risk4list,operator).floatValue();
                //保存结果
                resultList.add(risk0);
                resultList.add(risk1);
                resultList.add(risk2);
                resultList.add(risk3);
                resultList.add(risk4);
                //相加修正后的权重若和不为1,则归一化
                Float sum =0f;
                for (Float item:resultList){
                    sum += item;
                }
                if (sum != 1){//归一化
                    for(int l =0;l<resultList.size();l++){
                        Float temp = resultList.get(l)/sum;
                        resultList.set(l,temp);
                    }
                }
                temp_all.add(resultList);
            }else {
                temp_all.add(allbaserisks.get(end-1));
            }
        }
        //进行二级运算
        pseudoCodeFixing(list2,temp_all);
//        log.info("上一级模糊计算后的隶属度：{}",temp_all);
        return temp_all;
    }


    /**
     * Author:yjh
     * Description:<工具方法>进行动态权重修正：主要是对风险比较大的分项，进行权重的调整，将其权重调至最大。
     *                      总的来说，也就是增加高风险分项的重要程度，使项目的最终得分更具解释性。</工具方法>
     * Create date:2021/6/29 15:30
     * Param:[List<Float> weights,List<List<Float>> points]
     * Return:List<Float> weights[已修正过的]
     * Modify[]:,,
     */
    public List<Float> pseudoCodeFixing(List<Float> weights,List<List<Float>> points){

        if(weights.size()!=points.size()){
            log.info("权重修正_pseudoCodeFixing_Error!");
            return null;
        }
        log.info("weights:{}--points:{}",weights,points);
        List<Float> list_x5 = new ArrayList<>();//保存所有x5
        List<Float> list_x4x5 = new ArrayList<>();
        Float max_x5 = 0f;//取出x5最大的隶属度
        Float max_x4x5 = 0f;// 取出x4+x5的最大权重
        int index_m_x5 = 0;//对应下标
        int index_m_x4x5 = 0;
        int num =0;
        for (List<Float> item_point:points){
            list_x5.add(item_point.get(4));
            list_x4x5.add(item_point.get(3)+ item_point.get(4));
            if (max_x5 < item_point.get(4)){
                max_x5 = item_point.get(4);
                index_m_x5 = num;
            }
            if (max_x4x5 < item_point.get(3)+item_point.get(4)){
                max_x4x5 = item_point.get(3)+item_point.get(4);
                index_m_x4x5 = num;
            }
            num++;
        }
        Float max_weight = 0f;//取出最大权重
        Float semax_weight = 0f;//取出第二大权重
        for (Float weight:weights){
            if (max_weight < weight){
                semax_weight = max_weight;
                max_weight = weight;
            }else {
                if (semax_weight < weight){
                    semax_weight = weight;
                }
            }
        }
        int index_m_weight = weights.indexOf(max_weight);//保存下标
        int index_sem_weight = weights.indexOf(semax_weight);
//        log.info("max_x5:{},max_x4x5:{},max_weight:{},semax_weight:{},list_x5:{}",max_x5,max_x4x5,max_weight,semax_weight,list_x5);
//        log.info("list_maxx4x5:{}",list_x4x5);
        int ismaxx5 = isobjectOnlyOne(list_x5,max_x5);
        if (ismaxx5==1){
            //该对应项的权重不是最大权重
            if (max_x5 != max_weight){
                //1其对应权重=1.05*最大权重
                weights.set(index_m_x5, (float) (1.05*max_weight));
            }else {
                //该项对应的权重就是最大权重
                //不比第二大权重大1.05倍
                if (weights.get(index_m_x5) < 1.05*semax_weight){
                    //2其对应权重=1.05*第二大权重
                    weights.set(index_m_x5, (float) (1.05*semax_weight));
                }

            }
        }else if (ismaxx5==2) {
            //若X5有最大且不唯一
            //且X4+X5有最大且唯一
            if (isobjectOnlyOne(list_x4x5, max_x4x5) == 1) {
                if (max_x4x5 != max_weight) {
                    //3其对应权重=1.05*最大权重
                    weights.set(index_m_x4x5, (float) (1.05 * max_weight));
                } else {
                    //4#若X5有最大且不唯一，且X4+X5有最大且唯一，X4+X5最大对应的权重是最大权重且小于第二大权重的1.05倍
                    if (weights.get(index_m_x4x5) < 1.05 * semax_weight) {
                        weights.set(index_m_x4x5, (float) (1.05 * semax_weight));
                    }
                }
            }
        }else {
        //若X5无最大
            //x4+x5有最大隶属度
            if (max_x4x5!=0){
                //x4x5对应权重=最大权重
                weights.set(index_m_x4x5, max_weight);
            }
        }

        //相加修正后的权重若和不为1
        Float sum =0f;
        for (Float item:weights){
            sum += item;
        }
        if (sum != 1){//归一化
            for(int i =0;i<weights.size();i++){
                Float temp = weights.get(i)/sum;
                weights.set(i,temp);
            }
        }
        //返回注释
//        int i = 0;
//        for (Float item:weights){
//            i++;
//            log.info("weight[{}]:{}",i,item);
//        }

        return weights;
    }

    /**
     * Author:yjh
     * Description:判断列表是否包含是最大值的唯一元素
     * Create date:2021/6/29 21:31
     * Param:[List<Float> list,Float obj]
     * Return:1:表示只有一个最大值；2：表示有最大值且不唯一；0：表示无最大值
     * Modify[]:,,
     */
    private int isobjectOnlyOne(List<Float> list,Float obj){
        int i = 0;
        for (Float item:list){
            if (obj.equals(item)){
                i++;
            }
        }
        if (i==1){
            return 1;
        }else if (i>1&&i<list.size()){
            return 2;
        }else {
            return 0;
        }

    }

    /**
     * @Author chenhuanru
     * @Description //修正结果：隶属度数值由于进位原因，可能会产生误差
     *                修正规则：将误差加到隶属度数值最小的那一项
     * @Date 13:50 2020-12-05 13:50:26
     * @Param [risksList, precisionString]
     * @return java.util.List<java.lang.Float>
     **/
    @Override
    public List<Float> correctRisk(List<Float> risksList,String precisionString) {
        DecimalFormat df = new DecimalFormat(precisionString);
        List<Float> correctList = new ArrayList<>();
        float sum = 0f;
        float minVal = 1;
        float target = 1;
        int minIndex = -1;
        for(int i = 0;i<risksList.size();i++){
            float dfNum = Float.valueOf(df.format(risksList.get(i)));
            correctList.add(dfNum);
            sum += dfNum;
            if(minVal>dfNum){
                minVal = dfNum;
                minIndex = i;
            }
        }
        log.info("sum:{}",sum);
        float det = target - Float.valueOf(df.format(sum));
        if(det!=0){
            correctList.set(minIndex,Float.valueOf(df.format(minVal+det)));
        }
        return correctList;
    }

    @Override
    public List<Object> getNewItemByDepth(int nodeDepth,int preNum) {
        return newprefixsystemMapper.getItemByDepth(nodeDepth,preNum);
    }
    /**
     * @Author chenhuanru
     * @Description //float转double，自定义保留格式
     * @Date 10:40 2021-01-30 10:40:24
     * @Param [f, df]
     * @return java.lang.Double
     **/
    @Override
    public Double float2double(float f, DecimalFormat df) {
//        log.info("入参：{}",f);
        BigDecimal b = new BigDecimal(df.format(f));
        double d = b.doubleValue();
//        log.info("转double：{}",d);
        return d;
    }

    @Override
    public List<Newmembershipinfo> getAllNewMembership(Integer specialistId) {
        return newmembershipinfoMapper.getAllNewmembershipById(specialistId);
    }

    @Override
    public void addNewmemberShipInfo(Newmembershipinfo newmembershipinfo) {
        newmembershipinfoMapper.addNewmemberShipInfo(newmembershipinfo);
    }

    @Override
    public String addContractSpecialInfo(int client,int specialistId) {
        Contractspecialistinfo csi=new Contractspecialistinfo();
        csi.setContractId(client);
        csi.setSpecialistId(specialistId);
        ContractspecialistinfoMapper.insert(csi);
        return"SUCESS";
    }

    @Override
    public void editNewmemberShipInfo(Newmembershipinfo newmembershipinfo) {
        newmembershipinfoMapper.updateNewmemberShipInfo(newmembershipinfo);
    }

    @Override
    public void deleteNewmemberShipInfo(Integer mkey) {
        newmembershipinfoMapper.deleteNewmemberShipInfo(mkey);
    }
}
